import os

from util.path import init_session_path
from util import msg_template, msg_manage
from session_manage import SessionGitEuler4CVE, SessionDownload, SessionRpmRelease, SessionDownloadForSPEC, \
    SessionDownloadForCompatibilityReport


def git_src_from_gitee(req_json, db, sess_man):
    session_token = req_json.get('session_token', '')
    code_name = req_json.get('code_name', '')
    code_branch = req_json.get('code_branch', 'openEuler-20.03-LTS-SP1')
    msg = msg_template.MsgTemplateGitPull()
    msg.set_key_value("data", {"code_name": code_name, "code_branch": code_branch})
    path_session_one = init_session_path(session_token)
    msg.set_key_value("msg_type", "git_src_from_gitee")
    msg.set_key_value("msg_str", "Git拉取任务已建立")
    msg.set_key_value("session_token", session_token)
    res_json = msg.get_json()
    msg_manage.msg_write(res_json, session_token)
    sess = SessionGitEuler4CVE(code_name=code_name, code_branch=code_branch, path_session_one=path_session_one,
                               msg_manage=msg_manage, session_token=session_token, db=db)
    sess_man.join(sess)
    return res_json


def release_rpm_source(req_json, db, sess_man):
    session_token = req_json.get('session_token', '')
    rpm_file_path = req_json.get('rpm_file_path', '')
    filepath = os.path.join("static/session/", session_token, rpm_file_path)
    src_path = os.path.join("static/session/", session_token, "source_rpm",
                            rpm_file_path.replace('/', '_') + '.release')
    msg = msg_template.MsgTemplateForRpmRelease()
    msg.set_key_value("msg_str", "Rpm源码包提取任务已建立")
    msg.set_key_value("session_token", session_token)
    res_json = msg.get_json()
    msg_manage.msg_write(res_json, session_token)
    sess = SessionRpmRelease(filepath=filepath, src_path=src_path, msg_manage=msg_manage, session_token=session_token,
                             db=db, session_name="RPM包提取")
    sess_man.join(sess)
    return res_json


def download_file(req_json, db, sess_man):
    session_token = req_json.get('session_token', '')
    download_url = req_json.get('download_url', '')
    download_name = req_json.get('download_name', '')
    download_path_parent = req_json.get('download_path_parent', 'file_download')
    download_path = os.path.join("static/session/", session_token, download_path_parent)
    msg = msg_template.MsgTemplateForRpmRelease()
    msg.set_key_value("msg_str", "文件下载任务已建立")
    msg.set_key_value("session_token", session_token)
    res_json = msg.get_json()
    msg_manage.msg_write(res_json, session_token)
    sess = SessionDownload(download_url=download_url, download_path=download_path, download_name=download_name,
                           msg_manage=msg_manage, session_token=session_token, db=db, session_name="下载文件")
    sess_man.join(sess)
    return res_json


def download_file_spec(req_json, db, sess_man):
    session_token = req_json.get('session_token', '')
    download_url = req_json.get('download_url', '')
    download_name = req_json.get('download_name', '')
    download_path_parent = req_json.get('download_path_parent', 'file_download')
    download_path = os.path.join("static/session/", session_token, download_path_parent)
    msg = msg_template.MsgTemplateForRpmRelease()
    msg.set_key_value("msg_str", f"SPEC文件【{download_name}】下载任务已建立")
    msg.set_key_value("session_token", session_token)
    res_json = msg.get_json()
    msg_manage.msg_write(res_json, session_token)
    sess = SessionDownloadForSPEC(download_url=download_url, download_path=download_path, download_name=download_name,
                                  msg_manage=msg_manage, session_token=session_token, db=db, session_name="下载SPEC")
    sess_man.join(sess)
    return res_json


def generate_compatibility_report(req_json, db, sess_man):
    session_token = req_json.get('session_token', '')
    koji_link_list = req_json.get('task_koji_link', '')
    download_path_parent = req_json.get('download_path_parent', 'compatibility_report')
    download_path = os.path.join("static/session/", session_token, download_path_parent)
    msg = msg_template.MsgTemplateForCompatibilityReport()
    msg.set_key_value("msg_str", f"生成兼容性测试报告生成任务已建立")
    msg.set_key_value("session_token", session_token)
    res_json = msg.get_json()
    msg_manage.msg_write(res_json, session_token)
    for koji_link in koji_link_list.split('\n'):
        if koji_link == "" or koji_link.startswith('#'):
            continue
        task_id = koji_link.split('=')[-1]
        sess = SessionDownloadForCompatibilityReport(task_koji_link=koji_link, download_path=download_path,
                                                     msg_manage=msg_manage, session_token=session_token, db=db,
                                                     session_name=f"兼容性测试报告【{task_id}】",
                                                     mutex="generate_compatibility_report")
        sess_man.join(sess)
    return res_json


# koji -c koji_238.conf list-tagged v10-sp2-updates | grep rpm
# rpm-4.15.1-17.p01.ky10                    v10-sp2-updates       yangxudong

# [root@localhost sn]# koji -c koji_238.conf list-tagged --help
# Usage: koji list-tagged [options] <tag> [<package>]
# (Specify the --help global option for a list of other help options)
#
# Options:
#   -h, --help      show this help message and exit
#   --arch=ARCH     List rpms for this arch
#   --rpms          Show rpms instead of builds
#   --inherit       Follow inheritance
#   --latest        Only show the latest builds/rpms
#   --latest-n=N    Only show the latest N builds/rpms
#   --quiet         Do not print the header information
#   --paths         Show the file paths
#   --sigs          Show signatures
#   --type=TYPE     Show builds of the given type only. Currently supported
#                   types: maven, win, image
#   --event=EVENT#  query at event
#   --ts=TIMESTAMP  query at last event before timestamp
#   --repo=REPO#    query at event for a repo
# [root@localhost sn]#


# [root@localhost sn]# koji -c koji_238.conf list-builds --package=rpm
# Build                                                    Built by          State
# -------------------------------------------------------  ----------------  ----------------
# rpm-4.15.1-12                                            kojiadmin         COMPLETE
# rpm-4.15.1-12.ky10                                       kojiadmin         COMPLETE
# rpm-4.15.1-12.ky4                                        kojiadmin         COMPLETE
# rpm-4.15.1-12.oe1                                        kojiadmin         COMPLETE
# rpm-4.15.1-12.p01.ky10                                   yangxudong        COMPLETE
# rpm-4.15.1-23.p03.ky10                                   yangxudong        COMPLETE
# rpm-4.15.1-30.ky10                                       chengrui          COMPLETE
# rpm-4.15.1-32.kyh10                                      chengrui          FAILED
# rpm-4.15.1-36.ky10                                       yangxudong        COMPLETE
# rpm-4.15.1-36.p01.ky10                                   yangxudong        COMPLETE
# [root@localhost sn]#

# [root@localhost sn]# koji -c koji_238.conf list-builds --pattern=rpm*
# Build                                                    Built by          State
# -------------------------------------------------------  ----------------  ----------------
# rpm-4.15.1-12                                            kojiadmin         COMPLETE
# rpm-4.15.1-12.ky10                                       kojiadmin         COMPLETE
# rpm-4.15.1-12.ky4                                        kojiadmin         COMPLETE
# rpm-4.15.1-12.oe1                                        kojiadmin         COMPLETE
# rpm-4.15.1-12.p01.ky10                                   yangxudong        COMPLETE
# rpmlint-1.10-19.ky10                                     yangxiaodong      COMPLETE
# rpmreaper-0.2.0-20.ky10                                  kojiadmin         COMPLETE
# rpmrebuild-2.11-7.ky10                                   kojiadmin         COMPLETE
# rpmrebuild-2.11-7.ky4                                    kojiadmin         COMPLETE
# rpmrebuild-2.11-7.oe1                                    kojiadmin         COMPLETE
# rpmrebuild-2.15-1.ky10                                   yangxiaodong      COMPLETE
# [root@localhost sn]#

# ##### 前面查出软件包名字，然后加上 .src.rpm 用下面来查，结果中的 Build ID 对应网页中点进去的taskid
# [root@localhost sn]# koji -c koji_238.conf rpminfo rpm-4.15.1-12.ky10.src.rpm
# RPM: rpm-4.15.1-12.ky10.src [24196]
# RPM Path: /mnt/koji/packages/rpm/4.15.1/12.ky10/src/rpm-4.15.1-12.ky10.src.rpm
# SRPM: rpm-4.15.1-12.ky10 [4189]
# SRPM Path: /mnt/koji/packages/rpm/4.15.1/12.ky10/src/rpm-4.15.1-12.ky10.src.rpm
# Built: Sat, 14 Mar 2020 11:29:00 CST
# SIGMD5: e3d024af4446d7e729d17da06215dba5
# Size: 4256141
# License: GPLv2+
# Build ID: 4189
# Buildroot: 4713 (tag ky10-build, arch aarch64, repo 524)
# Build Host: builder1
# Build Task: 9968
# [root@localhost sn]#
